import 'package:flutter/material.dart';
import '../services/search_service.dart';
import '../models/song.dart';
import 'package:provider/provider.dart';
import '../providers/song_provider.dart';

class SearchView extends StatefulWidget {
  const SearchView({super.key});

  @override
  State<SearchView> createState() => _SearchViewState();
}

class _SearchViewState extends State<SearchView> {
  final TextEditingController _searchController = TextEditingController();
  List<Song> _searchResults = [];
  bool _isSearching = false;

  Future<void> _performSearch(String keyword) async {
    if (keyword.trim().isEmpty) {
      setState(() => _searchResults = []);
      return;
    }

    setState(() => _isSearching = true);
    try {
      final results = await SearchService.searchSongs(keyword);
      print("results: $results,keyword: $keyword");
      if (mounted) {
        setState(() {
          _searchResults = results;
          _isSearching = false;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('搜索失败: $e')),
        );
        setState(() => _isSearching = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        // 搜索框
        SizedBox(
          width: 280, // 固定搜索框宽度
          child: Container(
            height: 36,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(18),
            ),
            child: TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: '搜索歌曲...',
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(horizontal: 16),
                suffixIcon: _isSearching
                    ? const Padding(
                        padding: EdgeInsets.all(8.0),
                        child: SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        ),
                      )
                    : IconButton(
                        icon: const Icon(Icons.search),
                        onPressed: () => _performSearch(_searchController.text),
                      ),
              ),
              onSubmitted: _performSearch,
            ),
          ),
        ),

        // 搜索结果
        if (_searchResults.isNotEmpty)
          Expanded(
            child: Container(
              height: 36,
              padding: const EdgeInsets.only(left: 16),
              child: ListView.builder(
                scrollDirection: Axis.horizontal,
                itemCount: _searchResults.length,
                itemBuilder: (context, index) {
                  final song = _searchResults[index];
                  return Container(
                    margin: const EdgeInsets.only(right: 8),
                    child: Chip(
                      backgroundColor: Colors.white.withOpacity(0.9),
                      label: Text(
                        '${song.artist} - ${song.title}',
                        style: const TextStyle(fontSize: 12),
                      ),
                      deleteIcon: const Icon(Icons.add, size: 18),
                      deleteButtonTooltipMessage: "添加到播放列表",
                      onDeleted: () => _addSongToPlaylist(song),
                    ),
                  );
                },
              ),
            ),
          ),
      ],
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _addSongToPlaylist(Song song) async {
    final songProvider = Provider.of<SongProvider>(context, listen: false);
    await songProvider.createSong(
      await songProvider.database!,
      song.artist,
      song.title,
    );
    await songProvider.downloadSong(song);
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('已添加到播放列表并开始下载')),
      );
    }
  }
}
